package com.iqiyi.pps.epg.core.service.carousel;

import com.iqiyi.pps.epg.core.model.carousel.AutoCarouselEpisodeRule;

/**
 * Created by karkarrotxu on 2016/1/25.
 */
public class RuleNode {
    private RuleNode nextNode;
    private boolean firstSign = false;
    private boolean endSign = false;
    private int illegalCount;
    private AutoCarouselEpisodeRule rule;

    public RuleNode(AutoCarouselEpisodeRule rule) {
        this.rule = rule;
    }

    public RuleNode getNextNode() {
        return nextNode;
    }

    public AutoCarouselEpisodeRule getRule() {
        return rule;
    }

    public void setNextNode(RuleNode nextNode) {
        this.nextNode = nextNode;
    }

    public boolean isEmpty() {
        return false;
    }

    public boolean isFirstSign() {
        return firstSign;
    }

    public void setFirstSign(boolean firstSign) {
        this.firstSign = firstSign;
    }

    public boolean isEndSign() {
        return endSign;
    }

    public void setEndSign(boolean endSign) {
        this.endSign = endSign;
    }

    public RuleNode getCurrentUse() {
        RuleNode temp = this;
        do {
            if (temp.getRule().getCurrentExec() == 1) {
                return temp;
            } else {
                temp = temp.getNextNode();
            }
        } while (!temp.equals(this));
        return null;
    }


    public RuleNode getFirstNode() {
        RuleNode temp = this;
        do {
            if (temp.isFirstSign()) {
                return temp;
            } else {
                temp = temp.getNextNode();
            }
        } while (!temp.equals(this));
        return null;
    }

    public void addIllegalCount() {
        illegalCount++;
    }

    public AutoCarouselEpisodeRule doLoopEnd() {
        rule.setCurrentExec(0);
        return rule;
    }

    public AutoCarouselEpisodeRule doLoopStart() {
        rule.setCurrentExec(1);
        rule.setLastCreatedNo(0);
        return rule;
    }

    public boolean isSkip() {
        return illegalCount > 0 && illegalCount >= rule.getActualNum();
    }

    public RuleNode getNextAvailable() {
        RuleNode temp = this.getNextNode();
        while (!temp.equals(this)) {
            if (!temp.isSkip()) {
                return temp;
            } else {
                temp = temp.getNextNode();
            }
        }
        if (!this.isSkip()) {
            return this;
        }
        return null;
    }

}
